<template>
  <div>
    <el-button v-if="$hasPermission('sys:nextticket:advanced:rule')" plain size="small" style="margin-right:10px" @click="addCustomRule()">+ Advanced Rule</el-button>
    <el-dialog title="Advanced Rule" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <el-form v-loading="loading" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
        label-position="top">
        <el-form-item label="Rule Name:" prop="displayName">
          <el-input v-model="ruleForm.displayName"></el-input>
        </el-form-item>
        <el-form-item label="Rule Description:" prop="description">
          <el-input type="textarea" :rows="4" v-model="ruleForm.description"></el-input>
        </el-form-item>
        <el-form-item label="Rule:" prop="params">
          <advanced-filter v-if="dialogVisible" :ruleForm="ruleForm" :dataForm='ruleForm.params' :nextTicketType='nextTicketType' @testHandlerForCustomRule="testHandlerForCustomRule" v-bind="$attrs"
            :scriptItem='filterSetting.scriptItem' ref="advancedFilter" :gadgetSetting="gadgetSetting"></advanced-filter>
        </el-form-item>
        <el-form-item prop="params.points" :rules="{ required: true, message: this.$t('validate.greaterThanZero'), trigger: 'blur',pattern:/^[-+]?\d*\.?\d+$/}">
          Add <el-input style="width:100px" v-model="ruleForm.params.points"></el-input> Point
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :disabled="loading" size="mini" @click="handleClose">Cancel</el-button>
        <el-button v-if="$hasPermission('sys:nextticket:advanced:rule')" :disabled="loading" size="mini" type="primary" @click="submit">Save</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import advancedFilter from './advanced-filter/advanced-filter.vue'
import { filterJson } from './advanced-filter/filter-json'
export default {
  name: 'advanced-rule',
  props: ['nextTicketType', 'currentTemplateId', 'gadgetSetting'],
  components: {
    advancedFilter
  },
  data () {
    return {
      loading: false,
      dialogVisible: false,
      ruleForm: {
        name: `${this.nextTicketType.toUpperCase()}_CUSTOM_RULES_SERVICE`,
        displayName: '',
        description: '',
        enable: false,
        modelId: 0,
        params: {
          points: 1000,
          'filters': {
            'rules': [
              {
                'key': '',
                'opt': '',
                'type': 'text',
                'value': ''
              }
            ],
            'condition': 'and'
          }
        },
      },
      filterSetting: {
        scriptItem: filterJson,
        dataForm: {
          'filters': {
            'rules': [
              {
                'key': '',
                'opt': '',
                'type': 'text',
                'value': ''
              }
            ],
            'condition': 'and'
          }
        },
        queryParams: 'conditions',
        watermark: 'Select a Filter'
      },
      rules: {
        displayName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { min: 1, max: 70, message: this.$t('validate.length', { min: 1, max: 70 }), trigger: 'blur' }
        ],
        description: [
          { min: 0, max: 500, message: this.$t('validate.length', { min: 0, max: 500 }), trigger: 'blur' }
        ],
        params: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        'params.points': [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          // {
          //   validator: (rule, value, callback) => {
          //     if (value > 0) {
          //       callback();
          //     } else {
          //       callback(new Error(this.$t('validate.greaterThanZero')));
          //     }
          //   },
          //   trigger: 'blur',
          // },
        ],

      },
    }
  },
  methods: {
    addCustomRule (item) {
      this.$set(this.ruleForm,'modelId',this.currentTemplateId||0)
      if(item) {
        this.ruleForm = JSON.parse(JSON.stringify(item))
      }
      this.filterSetting.scriptItem.keyArray = this.gadgetSetting.customRuleKeyArray
      this.dialogVisible = true
    },
    handleClose () {
      this.$refs.ruleForm.resetFields()
      this.$refs.ruleForm.clearValidate()
      this.dialogVisible = false
      this.ruleForm= {
        name: `${this.nextTicketType.toUpperCase()}_CUSTOM_RULES_SERVICE`,
        displayName: '',
        description: '',
        enable: false,
        modelId: 0,
        params: {
          points: 1000,
          'filters': {
            'rules': [
              {
                'key': '',
                'opt': '',
                'type': 'text',
                'value': ''
              }
            ],
            'condition': 'and'
          }
        },
      }
      // Object.assign(this.$data, this.$options.data())
    },
    checkParams () {
      let _self = this
      let isPass = false
      function check (item) {
        let isCheck = true
        if((!item.value || item.value.length === 0)&&(item.value !== false)) {
          let res = _self.gadgetSetting.customRuleOptionList.filter(ii=>ii.type === item.type).find(i=>i.value === item.opt)
          if(res&&res.notValue) {
            isCheck = true
          } else {
            isCheck = false
          }
        }
        if (!item.key || !item.opt) {
          isCheck = false
        }
        return isCheck
      }
      try {
        for (let i = 0; i < _self.ruleForm.params.filters.rules.length; i++) {
          const item = _self.ruleForm.params.filters.rules[i];
          if (item.rules) {
            for (let j = 0; j < item.rules.length; j++) {
              isPass = check(item.rules[j]);
              if (!isPass) {
                break;
              }
            }
          } else {
            isPass = check(item);
          }
          if (!isPass) {
            break;
          }
        }

      } catch (error) {

      }
      return isPass
    },
    submit () {
      let isPass = this.checkParams()
      if (!isPass) {
        return this.$message.error(this.$t('validate.required'))
      }
      let _self = this
      _self.loading = true
      this.$refs.ruleForm.validate(res=>{
        if(res){
          _self.$interface.nextTicket.putAddCustomRuleApi(_self.ruleForm, _self.nextTicketType).then(({ data: res }) => {
            _self.loading = false
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.$message.success('Save Success')
            this.handleClose()
            this.$emit('getRuleList',this.ruleForm.modelId)
          })
        }else {
          _self.loading = false
        }
      })
    },
    testHandlerForCustomRule() {
      let isPass = this.checkParams()
      if (!isPass) {
        return this.$message.error(this.$t('validate.required'))
      }
      this.$emit('testHandlerForCustomRule',this.ruleForm)
    },
  }
}
</script>

<style scoped></style>
